package com.paireach.bw.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.blankj.utilcode.utils.NetworkUtils;
import com.paireach.bw.R;
import com.paireach.bw.activity.BackActivity;
import com.paireach.bw.activity.CommonActivity;
import com.paireach.bw.activity.KaActivity;
import com.paireach.bw.activity.StartTransActivity;
import com.paireach.bw.adapter.Frag1Adapter;
import com.paireach.bw.base.BaseFragment;
import com.paireach.bw.bean.DriveOrder;
import com.paireach.bw.event.AppEvent;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.WayBillRequest;
import com.paireach.bw.utils.JsonParse;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by ${cqc} on 2017/2/16.
 */

public class Frag1 extends BaseFragment implements View.OnClickListener, Frag1Adapter.OnItemClickListener {

    private static final String TAG = "Frag1";

    private View rootView;

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private Button btn;
    private List<DriveOrder> orderList = new ArrayList<>();
    private Frag1Adapter adapter;

    private boolean isViewCreated = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated) {
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(true);
                    onRefreshListener.onRefresh();
                }
            });
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.frag1, container, false);
        findViews();
        initViews();
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.setRefreshing(true);
        onRefreshListener.onRefresh();
    }

    private void findViews() {
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refreshLayout);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        btn = (Button) rootView.findViewById(R.id.btn_accept);
    }

    private void initViews() {
        refreshLayout.setColorSchemeResources(R.color.item3, R.color.item11, R.color.gold);
        refreshLayout.setOnRefreshListener(onRefreshListener);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
        adapter = new Frag1Adapter(orderList);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(this);

        btn.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }

    private SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new WayBillRequest().canAcceptOrderList(phoneNumber);
        }
    };


    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.CAN_ACCEPT_ORDER_LIST) {
            refreshLayout.setRefreshing(false);
            JsonParse.parseCanAcceptOrderList(event.getJson());
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.CAN_ACCEPT_ORDER_LIST) {
            refreshLayout.setRefreshing(false);
            orderList.clear();
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        if (event.getTag().equals("can_accept_order_list")) {
            if (event.getCode() == 0) {
                orderList.clear();
                adapter.notifyDataSetChanged();
                btn.setVisibility(View.GONE);
            } else if (event.getCode() == 1) {
                List<DriveOrder> orders = (List<DriveOrder>) event.getObj1();
                for (int i = 0; i < orders.size(); i++) {
                    orders.get(i).setSelect(false);
                }
                orderList.clear();
                orderList.addAll(orders);
                adapter.notifyDataSetChanged();
                btn.setVisibility(View.VISIBLE);
            } else {
                showToast(event.getExtraInfo());
            }
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if ("212".equals(orderList.get(position).getSTATUS())) {
            adapter.setOrderSelect(position);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_accept:
                if (NetworkUtils.isConnected()) {
                    List<DriveOrder> checkList = adapter.getSelectedOrderList();
                    for (int i = 0; i < orderList.size(); i++) {
                        if (orderList.get(i).getIsSelect()) {
                            checkList.add(orderList.get(i));
                        }
                    }
                    for (int i = 0; i < checkList.size(); i++) {
                        DriveOrder driveOrder = checkList.get(i);
                        if (!driveOrder.getSTATUS().equals("212")) {
                            showToast("该运单不是未接收运单");
                            return;
                        }
                    }
                    if (checkList.size() == 0) {
                        showToast("请选择运单");
                    } else if (checkList.size() == 1) {//只选择一个运单
                        Intent intent;
                        DriveOrder driverOrder = checkList.get(0);
                        String transType = driverOrder.getTRANSPORT_CODE();
                        if ("BACK".equals(transType)) {
                            intent = new Intent(context, BackActivity.class);
                        } else if ("COMMON".equals(transType)) {
                            intent = new Intent(context, CommonActivity.class);
                        } else {
                            intent = new Intent(context, KaActivity.class);
                        }
                        intent.putExtra("orderCode", driverOrder.getCODE());
                        startActivity(intent);
                    } else {//选择多个运单
                        ArrayList<String> strList = new ArrayList<>();
                        for (int i = 0; i < checkList.size(); i++) {
                            strList.add(checkList.get(i).getTRANSPORT_CODE());
                        }
                        if (strList.contains("BACK") || strList.contains("COMMON")) {
                            showToast("只有KA可以拼单");
                        } else {
//                            ArrayList<DriveOrder> driveOrders = new ArrayList<>();
                            StringBuffer sb = new StringBuffer();
                            for (int i = 0; i < checkList.size(); i++) {
                                DriveOrder info = checkList.get(i);
                                if (i == (checkList.size() - 1)) {
                                    sb.append(info.getCODE());
                                } else {
                                    sb.append(info.getCODE() + ",");
                                }
                            }
                            Intent intent = new Intent(context, KaActivity.class);
                            intent.putExtra("orderCode", sb.toString());
                            startActivity(intent);
                        }
                    }
                } else {
                    showToast("网络连接不可用，请稍后重试");
                }
                break;
        }
    }
}


